package mall.controller.client;

import mall.core.web.Controller;
import mall.entity.User;
import mall.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static mall.core.session.SessionKey.LOGIN_USER;

@WebServlet("/client/user")
public class ClientUserController extends Controller {

    private final UserService service = new UserService();


    private void profile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User loginUser = (User) req.getSession().getAttribute(LOGIN_USER);
        req.setAttribute("loginUser", loginUser);
        forward("/client/profile",req,resp);
    }

    public void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User loginUser = (User) req.getSession().getAttribute(LOGIN_USER);

        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");

        User user = new User();
        user.setId(loginUser.getId());
        user.setUsername(loginUser.getUsername());
        user.setPassword(loginUser.getPassword());
        user.setPhone(phone);
        user.setAddress(address);
        user.setName(name);
        user.setRole(loginUser.getRole());

        req.getSession().setAttribute(LOGIN_USER,user);

        service.update(user);

        redirect("/client/user?method=profile",req,resp);
    }
}
